package server;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * @Author: Eric.zhou
 * @Date: 2020/3/27 10:17
 */
public class BootStrap {
    private Map<String, HttpServlet> servletMap = new HashMap<String, HttpServlet>();
    private static Server server = new Server();
    // 加载解析相关的配置，web.xml


    private static int port = 8080;

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    private void start() throws Exception {
        initServer();
        loadServlet();

        // 定义一个线程池
        int corePoolSize = 10;
        int maximumPoolSize = 50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();


        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );

//
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("mincat start port:" + port);
        //tomcat1.0
//        while (true){
//            Socket accept = serverSocket.accept();
//            OutputStream outputStream = accept.getOutputStream();
//            String data = "hello mincat";
//            String httpHeader200 = HttpProtocolUtil.getHttpHeader200(data.getBytes().length)+data;
//            outputStream.write(httpHeader200.getBytes());
//            accept.close();
//        }

        //tomcat 2.0
//        while (true){
//            Socket accept = serverSocket.accept();
//            InputStream inputStream = accept.getInputStream();
//            Request request = new Request(inputStream);
//
//            Response response = new Response(accept.getOutputStream());
//            response.outputHtml(request.getUrl());
//            accept.close();
//        }

        /**
         * 完成Minicat 3.0版本
         * 需求：可以请求动态资源（Servlet）
         */
//        while(true) {
//            Socket socket = serverSocket.accept();
//            InputStream inputStream = socket.getInputStream();
//
//            // 封装Request对象和Response对象
//            Request request = new Request(inputStream);
//            Response response = new Response(socket.getOutputStream());
//
//            // 静态资源处理
//            if(servletMap.get(request.getUrl()) == null) {
//                response.outputHtml(request.getUrl());
//            }else{
//                // 动态资源servlet请求
//                HttpServlet httpServlet = servletMap.get(request.getUrl());
//                httpServlet.service(request,response);
//            }
//
//            socket.close();
//
//        }

        /**
         * 3.0 多线程 无线程池
         */
//        while(true) {
//            Socket socket = serverSocket.accept();
//            RequsetProcessor requsetProcessor = new RequsetProcessor(socket,servletMap);
//            requsetProcessor.start();
////            socket.close();
//
//        }
        /*
            多线程改造（使用线程池）
         */
        while (true) {

            Socket socket = serverSocket.accept();
            RequsetProcessor requestProcessor = new RequsetProcessor(socket, servletMap);
            //requestProcessor.start();
            threadPoolExecutor.execute(requestProcessor);
        }

    }

    /**
     * 加载解析server.xml
     */
    private void initServer() throws DocumentException {

        InputStream serverStream = this.getClass().getClassLoader().getResourceAsStream("server.xml");
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(serverStream);
        Element connect = (Element) document.selectSingleNode("Server/Service/Connector");
        String port = connect.attributeValue("port");
        Element host = (Element) document.selectSingleNode("Server/Service/Connector/Engine/Host");
        String name = host.attributeValue("name");
        String appBase = host.attributeValue("appBase");
        server.setHost(port);
        server.setHostname(name);
        server.setAppBase(appBase);
    }

    /**
     * 加载解析web.xml，初始化Servlet
     */
    private void loadServlet() throws FileNotFoundException, DocumentException, ClassNotFoundException, IllegalAccessException, InstantiationException {
        Mapper mapper = new Mapper();
        Host host = new Host();
        host.setHost(server.getHostname());
        mapper.setHosts(host);
        List<File> files = searchFiles(new File(server.getAppBase()), "web.xml");
        for (File file : files) {
            FileInputStream fileInputStream = new FileInputStream(file);
            SAXReader saxReader = new SAXReader();
            Document document = saxReader.read(fileInputStream);
            Element rootElement = document.getRootElement();

            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            for (int i = 0; i < selectNodes.size(); i++) {
                MinContext minContext = new MinContext();
                Element element = selectNodes.get(i);
                // <servlet-name>lagou</servlet-name>
                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();
                // <servlet-class>server.LagouServlet</servlet-class>
                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletclassElement.getStringValue();
                minContext.setMinContext(servletName);

                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                // /lagou
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
                servletMap.put(urlPattern, (HttpServlet) Class.forName(servletClass).newInstance());

            }

        }

    }


    public static void main(String[] args) throws IOException {
        BootStrap bootStrap = new BootStrap();
        try {
            bootStrap.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static List<File> searchFiles(File folder, final String keyword) {
        List<File> result = new ArrayList<File>();
        if (folder.isFile()) {
            result.add(folder);
        }


        File[] subFolders = folder.listFiles(new FileFilter() {
            @Override
            public boolean accept(File file) {
                if (file.isDirectory()) {
                    return true;
                }
                if (file.getName().toLowerCase().contains(keyword)) {
                    return true;
                }
                return false;
            }
        });

        if (subFolders != null) {
            for (File file : subFolders) {
                if (file.isFile()) {
                    // 如果是文件则将文件添加到结果列表中
                    result.add(file);
                } else {
                    // 如果是文件夹，则递归调用本方法，然后把所有的文件加到结果列表中
                    result.addAll(searchFiles(file, keyword));
                }
            }
        }
        return result;
    }
}
